#include "entry.h"

Entry::Entry(int player_number, std::string type_name, int x, int y, int time, int lems_to_spawn)
{
	m_sprite = new Sprite;

	// Parse the xml data.
	rapidxml::file<> entry_file(STANDARD_ENTRY_FILE.c_str());
    rapidxml::xml_document<> doc;
    doc.parse<0>(entry_file.data());

	// Get root node.
	rapidxml::xml_node<>* node = doc.first_node();

	bool entry_found = false;
	for(rapidxml::xml_node<> *entry_node = node->first_node("Entry"); entry_node; entry_node = entry_node->next_sibling())
	{
		// Try to find the entry in the list of entries.
		if (entry_node->first_attribute("name")->value() == type_name)
		{
			entry_found = true;

			// Load data from xml.
			int width = boost::lexical_cast<int>(entry_node->first_node("Width")->value());
			int height = boost::lexical_cast<int>(entry_node->first_node("Height")->value());
			std::string graphic = entry_node->first_node("Graphic")->value();
			int closed_animation_length = boost::lexical_cast<int>(entry_node->first_node("ClosedAnimationLength")->value());
			int opening_animation_length = boost::lexical_cast<int>(entry_node->first_node("OpeningAnimationLength")->value());
			int open_animation_length = boost::lexical_cast<int>(entry_node->first_node("OpenAnimationLength")->value());
			float animation_time = boost::lexical_cast<float>(entry_node->first_node("AnimationTime")->value());

			// Set size of the entry.
			m_size_x = width;
			m_size_y = height;

			// Create the animations.
			Animation closed_animation(graphic, width, height, 0, 0, closed_animation_length, animation_time);
			Animation opening_animation(graphic, width, height, 0 + width * closed_animation_length, 0, opening_animation_length, animation_time);
			Animation open_animation(graphic, width, height, 0 +  width * (closed_animation_length + opening_animation_length), 0, open_animation_length, animation_time);
			m_sprite->AddAnimation(closed_animation);
			m_sprite->AddAnimation(opening_animation);
			m_sprite->AddAnimation(open_animation);
		}
	}

	if (!entry_found)
	{
		LogManager::LogLine("Warning: Could not load entry with name '" + type_name + "'.");
	}

	m_sprite->SetCurrentAnimation(0);
	m_sprite->PlayAnimation();

	m_player_number = player_number;

	m_x = x;
	m_y = y;

	m_time = time;
	m_spawn_lems = false;
	m_new_lem = false;
	m_current_time = 0.0f;

	m_lems_spawned = 0;
	m_lems_to_spawn = lems_to_spawn;
}

Entry::~Entry()
{
	delete m_sprite;
}

void Entry::Open()
{
	m_sprite->SetCurrentAnimation(2);
	m_sprite->PlayAnimationOnce(1);
}

void Entry::Update(float timing_factor)
{
	m_sprite->set_x(m_x);
	m_sprite->set_y(m_y);
	m_sprite->Update(timing_factor);

	if (m_spawn_lems)
		m_current_time += timing_factor;

	if (m_current_time > m_time && m_lems_spawned < m_lems_to_spawn)
	{
		m_current_time -= m_time;
		m_lems_spawned++;
		m_new_lem = true;
	}
}

void Entry::Draw()
{
	m_sprite->Draw();
}